package com.wxm.killing.mq.bme;

import com.wxm.killing.mq.common.enums.HttpStatusEnum;
import com.wxm.killing.mq.common.exception.BaseException;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Description TODO
 * @author: wxm
 * @date: 2019/10/23 22:53
 * @version: 1.0
 */
public class BmeUtil {

    private static final Pattern ORDER_BY_PATTERN = Pattern.compile(
            "order\\s+by\\s+[^,\\s]+(\\s+asc|\\s+desc)?(\\s*,\\s*[^,\\s]+(\\s+asc|\\s+desc)?)*",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    /**
     * 拼接条件语句
     * @param map 条件参数  参数有3种类型，精确匹配 模糊匹配 区间范围
     * @param params 参数的值列表
     * @return
     */
    public static String appendWhereCondition(Map<String, Object> map, List<Object> params){
        StringBuilder conditionSql = new StringBuilder();
        //拼接精确匹配查询条件
        if(map.containsKey(BmeParam.EQUALS)){
            Map<String, Object> mapEqual = (Map<String, Object>) map.get(BmeParam.EQUALS);
            for (Map.Entry<String, Object> entry : mapEqual.entrySet()){
                conditionSql.append(" and ").append(entry.getKey() + " = ?");
                params.add(entry.getValue());
            }
        }
        //拼接模糊匹配查询条件
        if(map.containsKey(BmeParam.LIKE)){
            Map<String, Object> mapLike = (Map<String, Object>) map.get(BmeParam.LIKE);
            for (Map.Entry<String, Object> entry : mapLike.entrySet()){
                conditionSql.append(" and ").append(entry.getKey() + " like ?");
                params.add("%" + entry.getValue() + "%");
            }
        }
        //拼接区间查询条件暂停
        return conditionSql.toString();
    }

    /**
     * 获取当前页
     * @param map
     * @return
     */
    public static int getCurrentPage(Map<String, Object> map){
        int currentPage = 1;
        Object currentPageObject = map.get(Constant.CURRENT_PAGE);
        if(currentPageObject instanceof Integer){
            currentPage = (int) currentPageObject;
        }else{
            throw new BaseException(HttpStatusEnum.PARAM_PAGE_ERROR);
        }
        return currentPage;
    }

    /**
     * 获取每页大小,最大1000
     * @param map
     * @return
     */
    public static int getPageSize(Map<String, Object> map){
        int pageSize = 10;
        Object pageSizeObject = map.get(Constant.PAGE_SIZE);
        if(pageSizeObject instanceof Integer){
            pageSize = (int) pageSizeObject;
        }else{
            throw new BaseException(HttpStatusEnum.PARAM_PAGE_ERROR);
        }
        if(pageSize > 1000){
            pageSize = 1000;
        }
        return pageSize;
    }

    /**
     * 替换掉排序语句
     * @param sql
     * @return
     */
    public static String replaceOrderBy(String sql) {
        return ORDER_BY_PATTERN.matcher(sql).replaceAll("");
    }
}
